package com.cysion.study.ui.pteacher

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.PCourseDetailAdapter
import com.cysion.study.entity.FamilyeduAppointEntity
import com.cysion.study.entity.FamilyeduCelcrsEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.ui.POrderDetailActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.targetfun._subscribe
import com.scwang.smartrefresh.layout.constant.RefreshState
import kotlinx.android.synthetic.main.activity_pcourse_detail.*

class PCourseDetailActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.activity_pcourse_detail
    }

    private var objectId=""
    override fun initView() {
        objectId = intent.extras.getString("objectId")
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            initElements(TopBar.ELEMENT.IMG, TopBar.ELEMENT.TEXT, TopBar.ELEMENT.IMG)
            setTitle("课程管理")
            setTitleColor(color(R.color.black))
            setRightImg(R.mipmap.icon_course_detail_r)
            setOnTopBarClickListener { obje, pos ->
                if (pos == TopBar.Pos.RIGHT) {
                    //课程  跳 课程详情
                    var bundle = Bundle()
                    bundle.putString("orderId", obj.orderNo)//
                    bundle.putString("byType","1")//byType1 根据订单号请求订单详情，2订单id请求订单详情
                    UIHelper.jump(self, POrderDetailActivity::class.java,bundle)//订单详情
                } else if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        initRecyclerView()
        initRefreshLayout()
        tv_submit.setOnClickListener(this)
        tv_phone.setOnClickListener(this)
        tv_address.setOnClickListener(this)



    }

    private var obj=FamilyeduAppointEntity()
    private fun getfamilyeduAppoint() {
        ApiClient.api.familyeduAppoint(UserCache.token,objectId).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    obj=it
                    tv_name.text = obj.stuNickName
                    Glide.with(self).load(obj.stuHeadImage).apply(
                        RequestOptions().placeholder(R.mipmap.default_head)
                    ).into(iv_head)
                    tv_num.text = obj.canceledNum + "/" + obj.totalNum
                    tv_phone.text = obj.familyLink
                    tv_address.text = obj.supplement + " " + obj.address

                    initTopbar()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private fun initTopbar() {
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            initElements(TopBar.ELEMENT.IMG, TopBar.ELEMENT.TEXT, TopBar.ELEMENT.IMG)
            setTitle(obj.stuNickName)
            setTitleColor(color(R.color.black))
            setRightImg(R.mipmap.icon_course_detail_r)
            setOnTopBarClickListener { obje, pos ->
                if (pos == TopBar.Pos.RIGHT) {
                    //课程  跳 课程详情
                    var bundle = Bundle()
                    bundle.putString("orderId", obj.orderNo)//
                    bundle.putString("byType","1")//byType1 根据订单号请求订单详情，2订单id请求订单详情
                    UIHelper.jump(self, POrderDetailActivity::class.java,bundle)//订单详情
                } else if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
    }


    private lateinit var mAdapter: PCourseDetailAdapter
    private val dataList: MutableList<FamilyeduCelcrsEntity> = mutableListOf()
    private var curPage = 1

    override fun initData() {
        super.initData()
        smartLayout.autoRefresh()
    }

    //    初始化刷新控件
    private fun initRefreshLayout() {
        smartLayout.setOnRefreshListener {
            curPage = 1
            getfamilyeduAppoint()
            getDataList()
            smartLayout.setEnableLoadMore(true)

        }
        smartLayout.setOnLoadMoreListener {
            getDataList()
        }
    }

    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        mAdapter = PCourseDetailAdapter(dataList, Box.context)
        rv_list.adapter = mAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)
        mAdapter.setOnTypeClickListener { obj, position, flag ->
            //flag 1提醒，2撤销
            if (flag == 1) {//
                Alert.agreeDialog(this, "消课提醒", "2", "", "发送通知提醒家长进行消课\n" +
                        "（如果该用户7天内未点击确认，则系统会自动消课）","提醒") { confirm, num ->
                    if (confirm == CONFIRM) {
                        weekCourseNotice(obj.id)
                    }
                }
            } else if (flag == 2) {
                Alert.agreeDialog(this, "撤销消课", "2", "", "您确定要撤销本次消课申请么？","撤销") { confirm, num ->
                    if (confirm == CONFIRM) {
                        cancelCourseNotice(obj.id)
                    }
                }

            }
        }
        //模拟数据
        /*if (mAdapter.itemCount == 0) {
            var lists: MutableList<String> = mutableListOf("","","","","","","","","","","","","","","")
            dataList.addAll(lists)
            mAdapter.notifyDataSetChanged()
        }*/
    }

    //消课提醒
    private fun weekCourseNotice(id: String) {
        Alert.loading(this)
        ApiClient.api.cancelCourseNotice(id, UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("成功发送提醒")
                    smartLayout.autoRefresh()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }
    }

    //撤销消课
    private fun cancelCourseNotice(id: String) {
        Alert.loading(this)
        ApiClient.api.cancelCelcrs(id, UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("撤消成功")
                    smartLayout.autoRefresh()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }
    }

    private fun getDataList() {
        Alert.loading(this)
        stopRefresh()
        ApiClient.api.familyeduCelcrs(UserCache.token, objectId, curPage.toString(), "10")
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    if (curPage == 1) {
                        dataList.clear()
                        if (it.size == 0) {
                            multiView.showEmpty()
                        }
                    }
                    if (it.size <= 0) {
                        smartLayout.setEnableLoadMore(false)
                    } else {
                        curPage++
                        dataList.addAll(it)
                        mAdapter.notifyDataSetChanged()
                        multiView.showContent()
                    }

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }
    }

    private fun stopRefresh() {
        if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }
    }

    override fun closeMvp() {
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_address -> {
                if (TextUtils.isEmpty(obj.latitude) || TextUtils.isEmpty(obj.supplement)) {
                    ShowToast("未返回地址信息 不能导航")
                    return
                }
                UIHelper.goToBaidu(
                    this,
                    obj!!.latitude,
                    obj!!.longitude,
                    obj!!.supplement + obj!!.address
                )
            }
            R.id.tv_phone -> {
                if (TextUtils.isEmpty(obj.phoneReal)) {
                    ShowToast("系统未返回真实号码")
                    return
                }
                //拨打电话
                val intent = Intent()
                intent.action = Intent.ACTION_DIAL//dial是拨号的意思
                intent.data = Uri.parse("tel:" + obj!!.phoneReal)//这个tel不能改，后面的数字可以随便改
                startActivity(intent)
            }
            R.id.tv_submit -> {
                Alert.cancelCourse(this, "授课完成", "消耗课时数量", "", "消课") { confirm, num ->
                    if (confirm == CONFIRM) {
                        if (TextUtils.isEmpty(num)) {
                            ShowToast("请输入消课数量")
                            return@cancelCourse
                        }
                        //输入大于剩余课程数量的数点击消课后，提示：无法对大于剩余课程数的课程进行消课
                        /*if (num.toInt() > obj!!.totalNum.toInt()) {
                            ShowToast("无法对大于剩余课程数的课程进行消课")
                            return@cancelCourse
                        }*/
                        cancelCourse(num)
                    }
                }
            }
        }
    }

    //消课
    private fun cancelCourse(num: String) {
        ApiClient.api.cancelCourse(obj!!.id, num, UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("提交消课成功")
//                    finish()
                    smartLayout.autoRefresh()
                }
                _onError {
//                    Alert.close()
                    val handle = ErrorHandler.handle(it)
                    ShowToast(handle.errorMsg)
                }
            }
    }

}
